package me.acomma.groot.interfaces.controller;

import lombok.extern.slf4j.Slf4j;
import me.acomma.groot.application.auth.LoginCommand;
import me.acomma.groot.infrastructure.RestResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {
    @PostMapping("/login")
    public RestResult login(@RequestBody LoginCommand command) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword());
            subject.login(token);
            Serializable sessionId = subject.getSession().getId();
            return RestResult.success(sessionId);
        } catch (AuthenticationException e) {
            return RestResult.failure();
        }
    }

    @PostMapping("/logout")
    public RestResult logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return RestResult.success();
    }
}
